import { Component, OnInit, Input } from '@angular/core';
import { environment } from '@env/environment';
import { _HttpClient } from '@delon/theme';
import { DomSanitizer } from '@angular/platform-browser';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { DatePipe } from '@angular/common';

@Component({
    selector: 'app-monthwork-detail',
    templateUrl: './monthwork.detail.component.html',
    styleUrls: ['./monthworkarea.component.less'],
})
export class MonthworkDetailComponent implements OnInit {
    tableData = [];
    dateTh = [];
    lockHeadScroll = { x: '2200px', y: window.innerHeight - 350 + 'px' };
    iframeSrc;
    tableDetailData = [];
    planDetail = false;
    // tableData_mx = [];
    paramNid = '';
    wcqkData: any = {};
    nId: any = '';
    statusList = {
        '0': '未完成',
        '1': '已完成',
    }
    searchParam: any = {};
    weekList: any = [
        { value: '1', label: '第1周' },
        { value: '2', label: '第2周' },
        { value: '3', label: '第3周' },
        { value: '4', label: '第4周' },
        { value: '5', label: '第5周' }
    ];
    allChecked = false;
    indeterminate = false;

    @Input()
    set inputParam(v) {
        if (v.N_ID) {
            this.nId = v.N_ID
            this.paramNid = v.N_ID;
            this.query({ nId: v.N_ID });
            // this.query_mx({ pnid: v.N_ID });
            this.detail(v.N_ID);
        }
        if (v.VC_CJ) {
            switch (v.VC_CJ) {
                case '0':
                    this.planDetail = false;
                    break;
                default:
                    this.planDetail = true;
                    break;
            }
        }
        // this.showWcfk = v.VC_STATUS === '4' ? true : false;
        const src = `/csmis/prod/monthplan/WAMONTHPLANDQueryResult.jsp?detail=bianzhi` +
            `&nId=${v.N_ID}&nyear=${v.N_YEAR}&nmonth=${v.N_MONTH}` +
            `&orgId=${v.VC_ORG$ID}&stat=${v.VC_STATUS}&vcCj=${v.VC_CJ}&orgtype=${v.orgtype || ''}`;
        this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(src);
    };

    constructor(
        private http: _HttpClient,
        public sanitizer: DomSanitizer,
        private modalService: NzModalService,
        private message: NzMessageService,
        private datePipe: DatePipe
    ) { }

    ngOnInit(): void {
        this.initDateTh();
    }
    search() {
        let params = '';
        for (const item of Object.keys(this.searchParam)) {
            const data = this.searchParam[item];
            if (data || data === 0) {
                params += '&' + item + '=' + data;
            }
        }
        const url = environment.apiBase + '/csmis/ymVwaMonthplan/findByPnid.jwt?pnid=' + this.paramNid + params;
        this.http.get(url).subscribe(res => {
            this.tableDetailData = res;
        });
    }
    initDateTh() {
        for (let index = 0; index < 31; index++) {
            const name = index < 9 ? '0' + (index + 1) : (index + 1) + '';
            this.dateTh.push(name);
        }
    }

    getChecked() {
        const rows = this.tableDetailData.filter(row => row.checked);
        return rows;
    }

    wcqkDateChange(v) {
        this.wcqkData.vcFinishdate = this.datePipe.transform(v, 'yyyy-MM-dd');
    }

    wanChengFanKui(content) {
        this.wcqkData = {
            vcFinish: '1'
        };
        const rows = this.getChecked();
        if (!rows.length) {
            this.message.warning('请选择一项进行操作');
            return;
        }
        let check: any = true;
        rows.forEach(row => {
            if (row.vcFinish === '1') {
                check = false;
            }
        });
        if (check === false) {
            this.message.warning('您不能对已完成的条目进行完成反馈操作');
            return;
        } 
        this.modalService.confirm({
            nzTitle: `完成反馈`,
            nzWidth: '600',
            nzContent: content,
            nzOnOk: () => {
                const checkIds = [];
                rows.forEach(row => {
                    checkIds.push(row.nid)
                });
                const param: any = {
                    ids: checkIds.join(','),
                    vcFinish: this.wcqkData.vcFinish || '',
                    vcFinished: this.wcqkData.vcFinished || '',
                };
                if (this.wcqkData.vcFinishdate) {
                    param.vcFinishdate = this.wcqkData.vcFinishdate;
                }
                this.wcfk(param).subscribe(res => {
                    if (res === 'success') {
                        this.message.success('操作成功')
                        this.detail(this.nId);
                    } else {
                        this.message.warning('操作失败')
                    }
                })
            }
        }) 
    }

    // checkAll(v) {
    //     this.tableData.forEach(row => {
    //         row.checked = v;
    //     });
    // }

    currentPageDataChange($event: Array<{ name: string; age: number; address: string; checked: boolean; disabled: boolean; }>): void {
        this.tableDetailData = $event;
        this.refreshStatus();
    }

    refreshStatus(): void {
        const allChecked = this.tableDetailData.filter(value => !value.disabled).every(value => value.checked === true);
        const allUnChecked = this.tableDetailData.filter(value => !value.disabled).every(value => !value.checked);
        this.allChecked = allChecked;
        this.indeterminate = (!allChecked) && (!allUnChecked);
    }

    checkAll(value: boolean): void {
        this.tableDetailData.forEach(data => {
            if (!data.disabled) {
                data.checked = value;
            }
        });
        this.refreshStatus();
    }

    tabChange(e) {
        switch (e.index) {
            case 1:
                this.query({ nId: this.paramNid });
                break;
            case 2:
                this.detail(this.paramNid);
                break;
        }
    }
    // /**
    //  * pnid 取所选记录N_ID
    //  */
    // query_mx(param) {
    //     const url = environment.apiBase + '/csmis/ymVwaMonthplan/findByPnid.jwt';
    //     this.tableData_mx = [];
    //     this.http.get(url, param).subscribe(res => {
    //         this.tableData_mx = res;
    //     });
    // }

    /**
     * nId 取所选记录N_ID
     */
    query(param) {
        const url = environment.apiBase + '/csmis/ymVwaMonthplan/getMonthplancons.jwt';
        this.http.get(url, param).subscribe(res => {
            this.tableData = res.data.rows;
        });
    }
    /**
     * 完成反馈
     * vcFinish=0
     * vcFinished=测试
     * vcFinishdate=2020-04-13
     * ids=998545
     */
    wcfk(param) {
        const url = environment.apiBase + '/csmis/ymVwaMonthplan/updatemonthplan.jwt';
        return this.http.get(url, param, { responseType: 'text' });
    }
    detail(nid) {
        const url = environment.apiBase + '/csmis/ymVwaMonthplan/findByPnid.jwt?pnid=' + nid;
        this.http.get(url).subscribe(res => {
            this.tableDetailData = res;
        });
    }

}